<template>
	<div ref="chart" class="content" :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onBeforeUnmount, watch, ref, nextTick } from 'vue';
import moment from 'moment';

const animationDuration = 1000;

const props = defineProps({
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100%'
	},
	type: {
		type: String,
		default: ''
	},
	seriesName: {
		type: String,
		default: ''
	},
	chartData: {
		type: Array,
		default: () => []
	}
});

const chart = ref(null);

const initChart = () => {
	console.log(props, 'props');
	if (!chart.value) {
		chart.value = echarts.init(document.querySelector('.content'));
	}

	let xArr = [];
	let seriesData = [];
	if (props.type !== 'static') {
		if (props.type === 'beat') {
			seriesData = props.chartData.map(val => val.totalYield);
			xArr = props.chartData.map(val => moment(val.time).format('HH:mm'));
		} else {
			seriesData = props.chartData.map(val => val.yield);
			xArr = props.chartData.map(val => moment(val.startTime).format('HH:mm') + '~' + moment(val.endTime).format('HH:mm'));
		}
	} else {
		props.chartData.forEach(val => (xArr = Object.keys(val)));
		xArr.forEach((val, i) => {
			seriesData.push(props.chartData[0][xArr[i]]);
		});
	}

	let type = 'line';
	if (props.seriesName === '设备生产') {
		type = 'bar';
	}

	let series = [
		{
			name: props.seriesName,
			type,
			itemStyle: {
				color: '#75d874'
			},
			data: seriesData,
			animationDuration
		}
	];

	chart.value.setOption({
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		legend: {
			show: false
		},
		grid: {
			top: 30,
			left: '2%',
			right: '2%',
			bottom: '3%',
			containLabel: true
		},
		xAxis: [{
			type: 'category',
			axisLine: {
				lineStyle: {
					color: '#B6B6B4'
				}
			},
			data: xArr,
			axisTick: {
				alignWithLabel: true
			}
		}],
		yAxis: [
			{
				type: 'value',
				name: '',
				axisLine: {
					lineStyle: {
						color: '#B6B6B4'
					}
				},
				axisLabel: {
					formatter: '{value}'
				}
			}
		],
		series
	});
};

onMounted(() => {
	nextTick(() => {
		initChart();
	});
});

onBeforeUnmount(() => {
	if (chart.value) {
		chart.value.dispose();
		chart.value = null;
	}
});

watch(() => props.chartData, () => {
	initChart();
}, {
	deep: true
});
</script>

<style scoped>
/* Your styles here */
</style>
